<?php

class Helpers_CategoryFilter extends Zend_Controller_Action_Helper_Abstract {

	const IS_PRESENT = 'is_present';
	const ORDER = 'order';
	const ORDER_DIRECTION = 'order_direction';
	
	public $view;
	
	public function categoryFilter($name) {

		
		if (isset($_COOKIE[self::IS_PRESENT])) {
			$this->getRequest()->setParam(self::IS_PRESENT, $this->getRequest()->getParam('is_present', $_COOKIE[self::IS_PRESENT]));
		}
		$isPresent = (bool)$this->getRequest()->getParam('is_present', false);
		
		$orderTypes = array(
			'rank' => 'Популярности',
			'price'=>'Цене',
			'name'=>'Алфавиту',
			'rating'=>'Рейтингу'
		);
		
		if (isset($_COOKIE[self::ORDER])) {
			$this->getRequest()->setParam(self::ORDER, $this->getRequest()->getParam(self::ORDER, $_COOKIE[self::ORDER]));
		}
		$order = $this->getRequest()->getParam(self::ORDER, 'default');
		if (!isset($orderTypes[$order]) ) {
			$order = 'default';
		}

		$this->view->order = $order;
		
		if (isset($_COOKIE[self::ORDER_DIRECTION])) {
			$this->getRequest()->setParam(self::ORDER_DIRECTION, $this->getRequest()->getParam('order_direction', $_COOKIE[self::ORDER_DIRECTION]));
		}

		switch($order){
			case "default":
				$sortType = 'desc';
				break;
			case "rank":
				$sortType = 'desc';
				break;
			case "price":
				$sortType = 'asc';
				break;
			case "name":
				$sortType = 'asc';
				break;
			case "rating":
				$sortType = 'desc';
				break;
		}

		$orderDirection = $this->getRequest()->getParam('order_direction', $sortType);

		$this->view->order_direction =  $orderDirection;

		
		if (isset($_COOKIE['per_page'])) {
			$this->getRequest()->setParam('per_page', $this->getRequest()->getParam('per_page'));
		}
		$per_page = (int)$this->getRequest()->getParam('per_page');
		$this->view->per_page = $per_page;
		
		$this->view->is_present = $isPresent;
		$this->view->order_types = $orderTypes;

		return $this->view->render($name);
		
	}

	
	public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
        return $this;
    }
}